﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace HB.Base
{
    /// <summary>
    /// xml序列化帮助类
    /// </summary>
    public class XmlSerializationHelper
    {
        static XmlSerializationHelper()
        {
            Setting = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                OmitXmlDeclaration = true,
            };
        }
        private static XmlWriterSettings Setting = null;
        /// <summary>
        /// 发生错误时
        /// </summary>
        public static event Action<Exception> OnErr;
        /// <summary>
        /// 序列化对象为xml， [XmlIgnore]可忽略属性， [XmlElement]可设置属性别名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Obj"></param>
        /// <param name="Result"></param>
        /// <returns></returns>
        public static bool SerialObject<T>(T Obj, out string Result) where T : class
        {
            bool r = false; Result = null;
            using (StringWriter str = new StringWriter())
            {
                using (XmlWriter xml = XmlWriter.Create(str, Setting))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    XmlSerializerNamespaces nameSpace = new XmlSerializerNamespaces();
                    nameSpace.Add(string.Empty, string.Empty);
                    try
                    {
                        xmlSerializer.Serialize(xml, Obj, nameSpace);
                        Result = str.ToString();
                        r = true;
                    }
                    catch (Exception ex)
                    {
                        OnErr?.Invoke(ex);
                    }
                }
            }
            return r;
        }
        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <param name="Instance"></param>
        /// <returns></returns>
        public static bool DeSerialObject<T>(string xml, out T Instance) where T : class, new()
        {
            bool r = false;
            Instance = null;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(xml);
            try
            {
                Instance = (T)xmlSerializer.Deserialize(sr);
                r = true;
            }
            catch (Exception ex)
            {
                OnErr?.Invoke(ex);
            }
            return r;
        }
    }
}
